package com.example.lib.muchthread;

/**
 * 死锁
 *
 * 同步中嵌套同步
 */

public class l_deadlock_141 {
    public static void main(String[] args) {
        Ticket141 runnable = new Ticket141();

        Thread t1 = new Thread(runnable);
        Thread t2 = new Thread(runnable);

        t1.start();
        try {Thread.sleep(10);} catch (InterruptedException e) {throw new RuntimeException(e);}
        runnable.flag = false;
        t2.start();
    }


}

class Ticket141 implements Runnable {

    private static int tick = 100;
    boolean flag = true;
    Object obj=new Object();
    @Override
    public void run() {

        if (flag) {
            while (true) {
                synchronized (obj) {
                   show();
                }
            }
        } else {
            while (true) {
                show();
            }
        }
    }

    public synchronized void show() {//锁对象是this
        synchronized (obj){
            if (tick > 0) {
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                System.out.println(Thread.currentThread().getName() + "......同步函数:" + tick--);
            }
        }
    }
}
